package com.sugo.seckill.aop.redis;

import com.sugo.seckill.lock.distributedlock.redis.RedissLockUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName LockAspect
 * @Description
 * @Author hubin
 * @Date 2021/3/25 20:13
 * @Version V1.0
 **/
@Component
@Scope
@Aspect
@Order(1)
public class LockRedisAspect {


    // 注入request
    @Autowired
    private HttpServletRequest request;

    // 定义service的切入点
    @Pointcut("@annotation(com.sugo.seckill.aop.redis.ServiceRedisLock)")
    public void lockAspect(){

    }
    //增强的方法
    @Around("lockAspect()")
    public Object around(ProceedingJoinPoint joinPoint){
        Object obj = null;

        // 获取killid
        String str = request.getRequestURI();
        String killId = str.substring(str.lastIndexOf("/")-1,str.lastIndexOf("/"));

        // 实现加锁
        boolean res = RedissLockUtil.tryLock("seckill_goods_lock_" + killId,
                TimeUnit.SECONDS,
                3,
                10);

        // 如果加锁成功
        try {
            if(res){
                // 执行业务
                obj = joinPoint.proceed();
            }


        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            // 必须进行锁的释放
            if(res){
                RedissLockUtil.unlock("seckill_goods_lock_" + killId);
            }
        }
        return obj;
    }
}

